package com.qiezi.util;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.NumberKeyListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import static com.qiezi.App.isDebug;

public class Util {


    private static float sNoncompatDensity;
    private static float sNoncompatScaledDensity;


    public static synchronized Long getVersionCode(Context context) {
        PackageManager packageManager = context.getPackageManager();
        int version = 0;
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            version = packageInfo.versionCode;
            return packageInfo.getLongVersionCode();
        } catch (Exception e) {
            e.printStackTrace();
            return 0l;
        } catch (NoSuchMethodError e){
            e.printStackTrace();
            return Long.valueOf(version);
        }
    }

    public static boolean saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片  dearxy是可以改的
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dearxy";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();

            //把文件插入到系统图库
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 适配
     *
     * @param activity
     * @param application
     */
    public static void setCustomDensity(@NonNull Activity activity, final Application application) {
        final DisplayMetrics appDisplayMetrics = application.getResources().getDisplayMetrics();
        if (sNoncompatDensity == 0){
            sNoncompatDensity = appDisplayMetrics.density;
            sNoncompatScaledDensity = appDisplayMetrics.scaledDensity;
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if (newConfig != null && newConfig.fontScale > 0){
                        sNoncompatScaledDensity = application.getResources().getDisplayMetrics().scaledDensity;
                    }
                }
                @Override
                public void onLowMemory() {

                }
            });
        }

        final float targetDensity = appDisplayMetrics.widthPixels / 360;
        final float targetScaledDensity = targetDensity * (sNoncompatScaledDensity / sNoncompatDensity);
        final int targetDensityDpi = (int) (160 * targetDensity);
        appDisplayMetrics.density = targetDensity;
        appDisplayMetrics.scaledDensity = targetScaledDensity;
        appDisplayMetrics.densityDpi = targetDensityDpi;

        final DisplayMetrics activityDisplayMotrics = activity.getResources().getDisplayMetrics();
        activityDisplayMotrics.density = targetDensity;
        activityDisplayMotrics.scaledDensity = targetScaledDensity;
        activityDisplayMotrics.densityDpi = targetDensityDpi;
    }



    /**
     * 激活键盘
     *
     * @param activity
     * @param editText 焦点EditText
     */
    public static void openKeybord(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 隐藏键盘
     * @param activity
     */
    public static void hideKeybord(Activity activity) {
        InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm.isActive()&&activity.getCurrentFocus()!=null){
            if (activity.getCurrentFocus().getWindowToken()!=null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     *
     * 判断是否为手机号
     *
     * @param phone
     * @return
     */

    public static boolean isPhone(String phone){
        if(phone.length() != 11 || phone.charAt(0) != '1'){
            return false;
        }
        return true;
    }



    /**
     *
     * 设置EditText为密码框类型
     *
     * @param etPassword
     * @param maxLenght     设置EditText最大输入字符长度
     */

    public static void setEditTextPasswordType(EditText etPassword,int maxLenght){
        setEditTextMaxLenght(etPassword,maxLenght);
        etPassword.setInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_TEXT_VARIATION_PASSWORD);
        setEditTextKeyListener(etPassword,0);
    }

    public static void setEditTextMaxLenght(EditText editText,int maxLenght){

        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLenght)});
    }


    public static void setEditTextKeyListener(EditText et,int model){
        String str="";
        int keyType = 128;
        switch (model){
            case 0:
                str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,./;'[]~!@#$%^&*()`<>?:\"{}";
                keyType = InputType.TYPE_TEXT_VARIATION_PASSWORD;
                break;
            case 1:
                str = "0123456789Xx";
                keyType = InputType.TYPE_CLASS_NUMBER;
                break;
        }
        final int type = keyType;
        final String rStr = str;
        et.setKeyListener(new NumberKeyListener() {
            public int getInputType()
            {
                //指定键盘类型
                return type;
            }

            protected char[] getAcceptedChars()
            {
                //指定接受字符
                return rStr.toCharArray();
            }
        });
    }


    /**
     *
     * 发送验证码
     *
     * @param act
     * @param etCaptcha         输入验证码的edittext
     * @param tvCaptcha         点击获取验证码的textview
     */
    static public Thread countDown(final Activity act, EditText etCaptcha, final TextView tvCaptcha){


        openKeybord(act,etCaptcha);

        tvCaptcha.setEnabled(false);
        tvCaptcha.setText("60s");
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int timeCount = 60;
                while (timeCount-- > 0){

                    try {
                        final int finalTimeCount = timeCount;
                        tvCaptcha.post(new Runnable() {
                            @Override
                            public void run() {
                                tvCaptcha.setText(finalTimeCount + "s");
                            }
                        });
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                        timeCount = -19;
                        break;
                    }
                }
                if (timeCount>-3){
                    tvCaptcha.post(new Runnable() {
                        @Override
                        public void run() {
                            tvCaptcha.setText("发送验证码");
                            tvCaptcha.setEnabled(true);
                        }
                    });
                }
            }

        });

        thread.start();

        return thread;
    }


}
